/*
 * Mmseg.cpp
 *
 *  Created on: 2017年7月12日
 *      Author: heqian
 */

#include "Mmseg.h"
#include <iostream>
#include <functional>

#include "../mmseg/MMSeg.h"
#include "../mmseg/EnumPos.h"
#include "../mmseg/Dictionary.h"

using namespace mmseg;
using namespace std;

Dictionary mJDic = Dictionary::getInstance();

JNIEXPORT void JNICALL Java_hmmseg_Hemmseg_init(JNIEnv *env, jobject object, jstring dicpath_) {
	const char* dicpath = env->GetStringUTFChars(dicpath_, NULL);
	mJDic.init(new DicFile(dicpath));
	env->ReleaseStringUTFChars(dicpath_, dicpath);
}

JNIEXPORT void JNICALL Java_hmmseg_Hemmseg_save(JNIEnv *env, jobject object, jstring savepath_) {
	const char* savepath= env->GetStringUTFChars(savepath_, NULL);
	mJDic.save(savepath);
	env->ReleaseStringUTFChars(savepath_, savepath);
	return;
}

JNIEXPORT jstring JNICALL Java_hmmseg_Hemmseg_show(JNIEnv *env, jobject object) {
	string out;
	mJDic.outWord([&](string word) {
		out.append( word ).append("\n ");
	});
	return env->NewStringUTF(out.c_str());
}

JNIEXPORT jstring JNICALL Java_hmmseg_Hemmseg_showpos(JNIEnv *env, jobject object) {
	string out;
	showAllPost([&](const char* pos, const char* text) {
		out.append(pos).append(" ").append(text).append("l");
	});
	return env->NewStringUTF(out.c_str());
}

JNIEXPORT jstring JNICALL Java_hmmseg_Hemmseg_parse(JNIEnv *env, jobject object, jstring text_) {
	const char *text = env->GetStringUTFChars(text_, NULL);
	MMSeg seg(text, &mJDic);
	string out;
	seg.start([&](int start, int len, EnumPos pos, string other) {
		out.append("{");
		out.append("\"word\":\"").append(seg.c_str(),start,len).append("\",");
		out.append("\"offset\":").append( std::to_string(start)).append( ",");
		out.append( "\"count\":").append(std::to_string(len) ).append(",");
		out.append("\"pos\":\"").append( posToString(pos)) .append( "\",");
		out.append( "\"other\":").append( other.size()?other:"null");
		out.append( "},");
	});

	env->ReleaseStringUTFChars(text_, text);
	return env->NewStringUTF(out.c_str());
}

JNIEXPORT void JNICALL Java_hmmseg_Hemmseg_add(JNIEnv *env, jobject object, jstring word_, jstring pos_, jstring other_) {
	const char *word = env->GetStringUTFChars(word_, NULL);
	const char *pos = env->GetStringUTFChars(pos_, NULL);
	const char *other = env->GetStringUTFChars(other_, NULL);
	mJDic.addWord(word, stringToPos((char*) pos), other);
	env->ReleaseStringUTFChars(word_, word);
	env->ReleaseStringUTFChars(pos_, pos);
	env->ReleaseStringUTFChars(other_, other);
}

